package com.wuuxiang.dynamic.mongo.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;

public class DynamicMongoBeanPostProcessor implements BeanPostProcessor {
    private static final Logger log = LoggerFactory.getLogger(DynamicMongoBeanPostProcessor.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    /**
     * 方法描述：去掉_class属性，没有意义，而且在Example.of的时候会作为查询条件导致无法重构包名类名，所以默认去掉
     *
     * @param bean
     * @param beanName
     *
     * @return Object
     * @author lff
     * @date 2022/8/23 12:30
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof MongoTemplate) {
            MongoConverter mongoConverter = ((MongoTemplate) bean).getConverter();
            if (mongoConverter instanceof MappingMongoConverter && mongoConverter.getTypeMapper().isTypeKey(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY)) {
                ((MappingMongoConverter) mongoConverter).setTypeMapper(new DefaultMongoTypeMapper(null));
            }
            log.info("MongoTemplate去掉_class完成：{}", beanName);
        }
        return bean;
    }
}